package com.jisu.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jisu.common.ResultVo;
import com.jisu.dto.AdminDTO;
import com.jisu.dto.LoginRequest;
import com.jisu.pojo.Admin;
import com.jisu.service.IAdminService;
import com.jisu.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@CrossOrigin(origins = "*")
public class AdminController {

    @Autowired
    private IAdminService iadminService;

    //登录,登陆成功返回token，如果result为201，则账号不存在，如果是202，则密码错误
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginRequest loginRequest) {
        ResultVo<String> result = iadminService.login(loginRequest);
        return result;
    }

    //快速验证token是否无效
    @GetMapping("/verify")
    public ResultVo<?> verifyToken(@RequestHeader("Authorization") String token) {
        if (JWTUtil.verify(token)) {
            return ResultVo.success("验证通过");
        } else {
            return ResultVo.fail("Token无效");
        }
    }

    //从token中获取用户信息
    @GetMapping("/getProfile")
    public ResultVo<Admin> getProfile(HttpServletRequest request) {
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(request.getHeader("Authorization"));
        String account = decodedJWT.getClaim("account").asString();
        Admin admin = iadminService.getOne(new QueryWrapper<Admin>().eq("account", account));
        return ResultVo.success("获取成功", admin);
    }



    //增：添加管理员
    @PostMapping("/addAdmin")
    public ResultVo<Admin> addAdmin(@RequestBody Admin admin) {
        admin.setCreatedTime(LocalDateTime.now());
        admin.setUpdatedTime(LocalDateTime.now());
        return iadminService.addAdmin(admin);
    }

    //删：删除管理员,可传入多id
    @DeleteMapping("/deleteAdmin")
    public ResultVo deleteAdmin(@RequestParam("ids") List<Integer> ids) {
        return iadminService.deleteAdmin(ids);
    }

    //改：修改管理员
    @PutMapping("/updateAdmin")
    public ResultVo<Admin> updateAdmin(@RequestBody Admin admin) {
        return iadminService.updateAdmin(admin);
    }


    //查：分页查询管理员,不传入默认显示所有信息，多条件查询/模糊查询，可根据id，账户，姓名，手机号，性别，状态查询
    @PostMapping("/getAdminInPage")
    public ResultVo<IPage<Admin>> getAdminInPage(@RequestBody(required = false) AdminDTO adminDTO) {
        return iadminService.getAdminInPage(adminDTO);
    }
}